const log = console.log.bind(console)

const e = function(selector) {
    let element = document.querySelector(selector)
    if (element === null) {
        let s = `选择器 ${selector} 写错了`
        log(s)
        return null
    } else {
        return element
    }
}

const es = function(selector) {
    let elements = document.querySelectorAll(selector)
    if (elements.length === 0) {
        let s = `选择器 ${selector} 写错了`
        log(s)
        return []
    } else {
        return elements
    }
}
const appendHtml = function(element, html) {
    element.insertAdjacentHTML('beforeend', html)
}

const bindEvent = function(element, eventName, callback) {
    element.addEventListener(eventName, callback)
}

const removeClassAll = function(className) {
    let selector = '.' + className
    let elements = es(selector)
    for (let i = 0; i < elements.length; i++) {
        let e = elements[i]
        log('classname', className, e)
        e.classList.remove(className)
    }
}

const bindAll = function(selector, eventName, callback) {
    let elements = es(selector)
    for (let i = 0; i < elements.length; i++) {
        let e = elements[i]
        bindEvent(e, eventName, callback)
    }
}

// find 函数可以查找 element 的所有子元素
const find = function(element, selector) {
    let e = element.querySelector(selector)
    if (e === null) {
        let s = `选择器 ${selector} 写错了`
        log(s)
        return null
    } else {
        return e
    }
}

const ensure = function(condition, message) {
    // 在条件不成立的时候, 输出 message
    if (!condition) {
        log('*** 测试失败', message)
    } else {
        log('*** 测试成功')
    }
}

const ensureEqual = function(a, b, message) {
    if (a !== b) {
        // log('测试失败', message)
        // 给变量穿衣服
        log(`${message}, (${a}) 不等于 (${b})`)
    } else {
        log('测试成功')
    }
}

const arrayEquals = function(a1, a2) {
    if (a1.length !== a2.length) {
        return false
    }
    for (let i = 0; i < a1.length; i++) {
        if (a1[i] !== a2[i]) {
            return false
        }
    }
    return true
}
const convertDuration = (time) => {
    // 计算分钟
    const minutes = "0" + Math.floor(time / 60)
    // 计算秒数
    const seconds = "0" + Math.floor(time - minutes * 60)
    return minutes.substr(-2) + ":" + seconds.substr(-2)
}

const CLOUD_URL = 'https://api.imjad.cn/cloudmusic'

module.exports = {
    'log': log,
    'e': e,
    'appendHtml': appendHtml,
    'convertDuration': convertDuration,
    'CLOUD_URL': CLOUD_URL
}
